package com.donger.common.idempotent.interceptor;

import com.donger.common.idempotent.annotation.Idempotent;
import com.donger.common.idempotent.service.IdempotentService;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * IdempotentInterceptor
 *
 * @author xyx
 * @date 2020-05-24 18:55
 */
public class IdempotentMethodInterceptor implements MethodInterceptor {

    private IdempotentService idempotentService;

    public IdempotentMethodInterceptor(IdempotentService idempotentService) {
        this.idempotentService = idempotentService;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        //获取幂等性注解对象
        Idempotent idempotent = invocation.getMethod().getAnnotation(Idempotent.class);
        //幂等性未启用
        if (!idempotent.enable()) {
            return invocation.proceed();
        }
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        // 非Web环境
        if (Objects.isNull(attributes)) {
            return invocation.proceed();
        }
        HttpServletRequest request = attributes.getRequest();
        idempotentService.checkToken(request);
        return invocation.proceed();
    }
}
